//
//  AsyncSocketViewController.m
//  Socket
//
//  Created by yan on 2016/12/9.
//  Copyright © 2016年 yan. All rights reserved.
//

#import "AsyncSocketViewController.h"
#import "GCDAsyncSocket.h"

#define HOST @"192.168.1.145"
#define PORT 8080

@interface AsyncSocketViewController ()<GCDAsyncSocketDelegate> {
    GCDAsyncSocket *asyncSocket;
}

@end

@implementation AsyncSocketViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    button.backgroundColor = [UIColor redColor];
    [button addTarget:self action:@selector(connect) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

- (void)connect {
    if (asyncSocket && [asyncSocket isConnected]) {
        NSString *requestStr = [NSString stringWithFormat:@"POST / HTTP/1.1\r\nHost: %@\r\n\r\n", HOST];
        
        NSData *requestData = [requestStr dataUsingEncoding:NSUTF8StringEncoding];
        [asyncSocket writeData:requestData withTimeout:-1 tag:1];
        return;
    }
    asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    NSError *error;
    [asyncSocket connectToHost:HOST onPort:PORT error:&error];
    NSLog(@"%@", error);
}

- (void)socket:(GCDAsyncSocket *)sock didReceiveTrust:(SecTrustRef)trust completionHandler:(void (^)(BOOL))completionHandler {
    //服务器自签名证书:
    //openssl req -new -x509 -nodes -days 365 -newkey rsa:1024  -out tv.diveinedu.com.crt -keyout tv.diveinedu.com.key
    
    //Mac平台API(SecCertificateCreateWithData函数)需要der格式证书，分发到终端后需要转换一下
    //openssl x509 -outform der -in tv.diveinedu.com.crt -out tv.diveinedu.com.der
    NSString *certFilePath1 = [[NSBundle mainBundle] pathForResource:@"tv.diveinedu.com" ofType:@"der"];
    NSData *certData1 = [NSData dataWithContentsOfFile:certFilePath1];
    
    OSStatus status = -1;
    SecTrustResultType result = kSecTrustResultDeny;
    
    if(certData1)
    {
        SecCertificateRef   cert1;
        cert1 = SecCertificateCreateWithData(NULL, (__bridge_retained CFDataRef) certData1);
        // 设置证书用于验证
        SecTrustSetAnchorCertificates(trust, (__bridge CFArrayRef)[NSArray arrayWithObject:(__bridge id)cert1]);
        // 验证服务器证书和本地证书是否匹配
        status = SecTrustEvaluate(trust, &result);
    }
    else
    {
        NSLog(@"local certificates could not be loaded");
        completionHandler(NO);
    }
    
    if ((status == noErr && (result == kSecTrustResultProceed || result == kSecTrustResultUnspecified)))
    {
        //成功通过验证，证书可信
        completionHandler(YES);
    }
    else
    {
        CFArrayRef arrayRefTrust = SecTrustCopyProperties(trust);
        NSLog(@"error in connection occured\n%@", arrayRefTrust);
        completionHandler(NO);
    }
    
}



- (void)socketDidSecure:(GCDAsyncSocket *)sock
{
    //    NSString *requestStr = [NSString stringWithFormat:@"GET / HTTP/1.1\r\nHost: %@\r\n\r\n", HOST];
    //
    //    NSData *requestData = [requestStr dataUsingEncoding:NSUTF8StringEncoding];
}

- (void)socket:(GCDAsyncSocket *)sock didConnectToUrl:(NSURL *)url {
    NSLog(@"url:%@", url);
}

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
    NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    [sock readDataWithTimeout:1 tag:0];
}

- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag {
    
}

- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err {
    
}

- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port {
    NSLog(@"host:%@", host);
    //    NSMutableDictionary *settings = [NSMutableDictionary dictionaryWithCapacity:3];
    //
    //    [settings setObject:@"www.paypal.com"
    //                 forKey:(NSString *)kCFStreamSSLPeerName];
    //
    //    [sock startTLS:settings];
    NSString *requestStr = [NSString stringWithFormat:@"GET / HTTP/1.1\r\nHost: %@\r\n\r\n", HOST];
    NSData *requestData = [requestStr dataUsingEncoding:NSUTF8StringEncoding];
    
    [sock writeData:requestData withTimeout:-1 tag:0];
    [sock readDataWithTimeout:-1 tag:0];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
